package com.qf.fc.Filter;

import com.alibaba.fastjson.JSONObject;
import com.qf.fc.utils.JwtUtils;
import com.qf.fc.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author zhangH
 * @Date 2024/12/19 11:13
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 首先，将请求和响应强转为http类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String url = request.getRequestURL().toString();
        log.info("当前请求地址是:{}",url);

        // 判断当前请求是否是登录请求
        if (url.contains("login")){
            log.info("该操作是登录操作，放行");
            filterChain.doFilter(request,response);
            return;
        }
        // 获取请求头中jwt令牌，进行检查
        String jwt = request.getHeader("token");
        log.info("当前获取到的Jwt令牌是：{}",jwt);

        // 检查令牌是否正确
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为null");
            R result = R.fail("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(result);
            response.getWriter().write(notLogin);
            return;
        }
        try {
            JwtUtils.parseJwt(jwt);
        }catch (Exception e){
            log.info("jwt令牌失效，未成功登录。");
            R result = R.fail("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(result);
            response.getWriter().write(notLogin);
            return;
        }
        // 令牌合法，放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);

    }
}
